package com.view.cn.mvprxjava.fragment.socket;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.view.cn.mvprxjava.R;
import com.view.cn.mvprxjava.fragment.BaseFragment;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 客户端socket
 * Created by Zengxiaoping on 2017/2/9.
 */

public class ClientSocketFragment extends BaseFragment implements View.OnClickListener{

	public static final String TAG = ClientSocketFragment.class.getSimpleName();

	private TextView mTv;
	private EditText mEdIPConnect;
	private Button mBtnStart;
	private Button mBtnSend;
	private Button mBtnStop;
	private EditText mEtSendContent;

	private Socket mSocket;
	private AcceptThread mAcceptThread;
	private ReceivceThread mReceivceThread;
	private boolean isConnect;
	private Timer mTimer;   //用于检测连接（心跳检测）

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				//建立链接
				case 0:
					mTv.setText("连接已建立");
					break;
				//接收数据
				case 1:
					mTv.setText(msg.obj.toString());
					break;
				//断开连接
				case -999:
					break;
			}
		}
	};

	public static ClientSocketFragment newInstance() {
		ClientSocketFragment fragment = new ClientSocketFragment();
		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_client, container, false);
		initView(view);
		return view;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}


	private void initView(View view) {
		mTv = (TextView) view.findViewById(R.id.tv);
		mEdIPConnect = (EditText) view.findViewById(R.id.edIPConnect);
		mBtnStart = (Button) view.findViewById(R.id.btnStart);
		mBtnSend = (Button) view.findViewById(R.id.btnSend);
		mBtnStop = (Button) view.findViewById(R.id.btnStop);
		mEtSendContent = (EditText) view.findViewById(R.id.etSendContent);

		mBtnStart.setOnClickListener(this);
		mBtnSend.setOnClickListener(this);
		mBtnStop.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			//建立连接
			case R.id.btnStart:
				isConnect = true;
				if (mAcceptThread == null) {
					mAcceptThread = new AcceptThread();
					mAcceptThread.start();
				}
				//延迟两秒，3分钟检测一次
				mTimer = new Timer();
				mTimer.schedule(new TimerTask() {
					@Override
					public void run() {
						//如果连接已经断开,重连
						if (mSocket != null && !mSocket.isConnected()) {
							try {
								mSocket = new Socket(mEdIPConnect.getText().toString(), 40002);
								//开启接受数据的线程
								mReceivceThread = new ReceivceThread(mSocket);
								mReceivceThread.start();
							} catch (Exception e) {
								e.printStackTrace();
							}
							if (mSocket != null && mSocket.isConnected()) {//成功连接获取socket对象则发送成功消息
								Message message = mHandler.obtainMessage();
								message.what = 0;
								mHandler.sendMessage(message);
							}
						}
					}
				}, 2000, 1000 * 20);
				break;
			//发送数据
			case R.id.btnSend:
				OutputStream outputStream = null;
				try {
					outputStream = mSocket.getOutputStream();
					outputStream.write((mEtSendContent.getText().toString() + "\n").getBytes("utf-8"));
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			//断开连接
			case R.id.btnStop:
				isConnect = false;
				try {
					mSocket.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
		}
	}

	//建立连接线程
	private class AcceptThread extends Thread {
		@Override
		public void run() {
			try {
				mSocket = new Socket(mEdIPConnect.getText().toString(), 40002);
				//开启接受数据的线程
				if (mSocket.isConnected()) {
					mReceivceThread = new ReceivceThread(mSocket);
					mReceivceThread.start();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (mSocket != null && mSocket.isConnected()) {//成功连接获取socket对象则发送成功消息
				Message message = mHandler.obtainMessage();
				message.what = 0;
				mHandler.sendMessage(message);
			}
		}
	}

	//接受数据线程
	private class ReceivceThread extends Thread {
		private InputStream mInputStream;

		public ReceivceThread(Socket socket) {
			try {
				mInputStream = socket.getInputStream();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void run() {
			while (isConnect) {
				InputStreamReader isr = new InputStreamReader(mInputStream);
				BufferedReader br = new BufferedReader(isr);
				try {
					Message msg = mHandler.obtainMessage();
					msg.what = 1;
					msg.obj = br.readLine();    //读服务器端发来的数据，阻塞直到收到结束符\n或\r
					mHandler.sendMessage(msg);
				} catch (Exception e) {
					isConnect = false;          //防止服务器端关闭导致客户端读到空指针而导致程序崩溃
					Message msg2 = mHandler.obtainMessage();
					msg2.what = -999;
					mHandler.sendMessage(msg2); //发送信息通知用户客户端已关闭
					e.printStackTrace();
				}
			}
		}
	}
}
